package com.whc.common.design.handle.type;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whc.common.Constant;
import com.whc.common.exception.MessageException;
import com.whc.vo.Column;
import com.whc.vo.ListColumn;
import com.whc.vo.Table;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author wang-hai-cheng
 * @since 2022/1/1 20:03
 */
public class PageChain extends TypeChain {

    @Override
    public Object handler(Map<String, Object> body) {
        if (!Constant.OP_TYPE.PAGE.equals(body.get(Constant.VARIABLE_NAME.TYPE))) {
            return handle.handler(body);
        }
        Table table = new Table(null, new ArrayList<>());
        List<Column> orders = new ArrayList<>();
        AtomicLong current = new AtomicLong(1L);
        AtomicLong size = new AtomicLong(10L);
        body.forEach((k, v) -> {
            if (k.equals("size")) {
                size.set(Long.parseLong(String.valueOf(v)));
            }
            if (k.equals("current")) {
                current.set(Long.parseLong(String.valueOf(v)));
            }
            if (v instanceof LinkedHashMap) {
                table.setTableName(k);
                ((LinkedHashMap<String, Object>) v).forEach((k1, v1) -> {
                    String type = columnType(k1);
                    ListColumn column = new ListColumn(k1.replace(type, ""), v1, type);
                    if ("desc".equals(type) || "asc".equals(type)) {
                        orders.add(column);
                    } else {
                        table.getColumns().add(column);
                    }
                });
            }
        });
        Page<Map<Object, Object>> page = new Page<>(current.get(), size.get());
        return commonMapper.page(page, table, orders);
    }

    private String columnType(String k) {
        if (k.contains(Constant.FLAG.UNEQUAL)) {
            return Constant.FLAG.UNEQUAL;
        }
        if (k.contains(Constant.FLAG.EQUAL)) {
            return Constant.FLAG.EQUAL;
        }
        if (k.contains(Constant.FLAG.NOT_IN)) {
            return Constant.FLAG.NOT_IN;
        }
        if (k.contains(Constant.FLAG.IN)) {
            return Constant.FLAG.IN;
        }
        if (k.contains(Constant.FLAG.LIKE)) {
            return Constant.FLAG.LIKE;
        }
        if (k.contains(Constant.FLAG.DESC)) {
            return "desc";
        }
        if (k.contains(Constant.FLAG.ASC)) {
            return "asc";
        }
        if (k.contains(Constant.FLAG.BETWEEN)) {
            return Constant.FLAG.BETWEEN;
        }
        throw MessageException.instance(Constant.Message.X_PWF_SB);
    }
}